import baseUrl from "./config";
let header = 'application/x-www-form-urlencoded;charset=UTF-8';

export default function request(api, method, data = {}) {
	let token = uni.getStorageSync('access_token');
	if (token) {
		data.access_token = token;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + api,
			method: method || "post",
			header: {
				'content-type': header
			},
			data: data,
			success: (res) => {
				let code = res.data.ret ? res.data.ret : res.statusCode
				if (code == 200) {
					// 请求详情log
					console.log(api + '\n', res.data)
					resolve(res.data)
				} else if (code == 30003 || code == 403) {
					uni.hideLoading();
					uni.showToast({
						title: '您的登录已过期',
						icon: 'none'
					})
					reject('登录已过期')
					setTimeout(() => {
						uni.clearStorageSync()
						uni.reLaunch({
							url: "/pages/public/login"
						})

					}, 1000);
				} else {
					uni.hideLoading();
					let msg = res.data.msg.split("：").slice(-1)[0]
					uni.showToast({
						title: msg,
						icon: 'none'
					})
					reject(res.data.msg || '系统错误');
				}
			},
			fail: (msg) => {
				uni.hideLoading();
				reject('请求失败');
			}
		})
	})
}

['get', 'post'].forEach((method) => {
	request[method] = (api, data) => request(api, method, data)
});